﻿using CTBU.DAO;
using CTBU.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Student.Areas.WebAPI.Controllers
{
    public class SysStudentController : Controller
    {
        private StudentDAO _stuDao = new StudentDAO();


        public JsonResult AddUser(string Name, int Score)
        {


            TbStudent newItem = new TbStudent();
            newItem.SName = Name;
            newItem.IScore = Score;


            _stuDao.Insert(newItem);

            return Json(new { ID = newItem.Id, Msg = "success" }, JsonRequestBehavior.AllowGet);


        }



        //AddOrUpdateUser
        public JsonResult AddOrUpdateUser(int Id, string Name, int Score)
        {
            if (Id < 0)
            {
                //新增


                TbStudent newItem = new TbStudent();
                newItem.SName = Name;
                newItem.IScore = Score;


                _stuDao.Insert(newItem);

                return Json(new { ID = newItem.Id, Msg = "success" }, JsonRequestBehavior.AllowGet);

            }
            else
            {
                //更新
                TbStudent oldItem = _stuDao.GetByID(Id);
                if (oldItem != null)
                {
                    oldItem.SName = Name;
                    oldItem.IScore = Score;
                    _stuDao.Update(oldItem);
                    return Json(new { ID = oldItem.Id, Msg = "success" }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { ID = -1, Msg = "读取用户出错，找不到用户！" }, JsonRequestBehavior.AllowGet);
                }


            }



        }


        public JsonResult getStudents()
        {




            IList<TbStudent> myList = _stuDao.GetAll();

            return Json(myList, JsonRequestBehavior.AllowGet);


        }

        //DelUser
        public JsonResult DelUser(int Id)
        {

            try
            {
                _stuDao.Del(Id);

                //TbStudent delStudent = _stuDao.GetByID(id);
                //_stuDao.Del(delStudent);


                return Json(new { ID = 1, Msg = "Success" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ee)
            {

                return Json(new { ID = -1, Msg = ee.Message }, JsonRequestBehavior.AllowGet);
            }



        }

    }
}
